<template>
  <div class="group-buy-add-container">
    <el-card title="新增团购活动">
      <!-- 表单主体 -->
      <el-form
          ref="groupBuyForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="group-buy-form"
          :disabled="isLoading"
      >
        <!-- 基础信息区域 -->
        <el-divider content="基础信息" />
        <el-form-item label="商户ID" prop="merchantId">
          <el-input v-model="formData.merchantId" disabled placeholder="自动获取当前商户ID" />
        </el-form-item>

        <el-form-item label="团购名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="请输入团购活动名称"
              maxlength="50"
              show-word-limit
              autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="团购描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入团购活动描述（可选）"
              maxlength="500"
              show-word-limit
              autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="团购原价" prop="price">
          <el-input
              v-model.number="formData.price"
              placeholder="请输入团购原价"
              type="number"
              step="0.01"
              min="0.01"
              autocomplete="off"
          >
            <template #prefix>
              <span style="margin-left: 8px; color: #666">¥</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="团购折扣价" prop="discount">
          <el-input
              v-model.number="formData.discount"
              placeholder="请输入团购折扣价"
              type="number"
              step="0.01"
              min="0.01"
              autocomplete="off"
          >
            <template #prefix>
              <span style="margin-left: 8px; color: #666">¥</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="每单限制人数" prop="personNum">
          <el-input
              v-model.number="formData.personNum"
              placeholder="请输入每单最大购买人数"
              type="number"
              min="1"
              autocomplete="off"
          />
          <div class="form-hint">注：每人限参与1次，填写1表示单人单团</div>
        </el-form-item>

        <!-- 商品选择区域 -->
        <el-divider content="选择商户商品" />
        <div class="goods-select-section">
          <el-card shadow="hover" style="margin-bottom: 16px;">
            <div class="card-header">
              <h4 style="margin: 0;">商户商品库（勾选后添加到已选列表）</h4>
            </div>
            <!-- 无商品提示 -->
            <div v-if="merchantGoodsList.length === 0 && !isLoading" class="no-merchant-goods">
              <el-icon class="icon">
                <ShoppingCart />
              </el-icon>
              <p>当前商户暂无商品，请先添加商品后再创建团购</p>
            </div>
            <el-table
                v-else
                :data="merchantGoodsList"
                border
                stripe
                size=""
                style="width: 100%; margin-top: 16px;"
                @selection-change="handleGoodsSelection"
                :loading="isLoading"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="商品ID" width="100" align="center" />
              <el-table-column prop="name" label="商品名称" width="250" align="center" />
              <el-table-column prop="price" label="商品单价" width="120" align="center">
                <template #default="scope">
                  ¥{{ formatPrice(scope.row.price) }}
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="100" align="center" />
              <el-table-column prop="categoryName" label="商品分类" width="150" align="center" />
            </el-table>
          </el-card>

          <!-- 已选商品列表 -->
          <el-card shadow="hover">
            <div class="card-header">
              <h4 style="margin: 0;">已选商品（至少选择1件）</h4>
            </div>
            <div v-if="selectedGoodsList.length === 0" class="no-selected-goods">
              <el-icon class="icon">
                <ShoppingCart />
              </el-icon>
              <p>暂无已选商品，请从上方商品库中选择</p>
            </div>
            <el-table
                v-else
                :data="selectedGoodsList"
                border
                stripe
                size=""
                style="width: 100%; margin-top: 16px;"
            >
              <el-table-column prop="name" label="商品名称" width="250" align="center" />
              <el-table-column prop="price" label="商品单价" width="120" align="center">
                <template #default="scope">
                  ¥{{ formatPrice(scope.row.price) }}
                </template>
              </el-table-column>
              <el-table-column prop="num" label="选择数量" width="150" align="center">
                <template #default="scope">
                  <el-input
                      v-model.number="scope.row.num"
                      type="number"
                      min="1"
                      :max="scope.row.stock"
                      @change="calculateTotalPrice"
                      placeholder="请输入数量"
                  />
                </template>
              </el-table-column>
              <el-table-column label="小计" width="120" align="center">
                <template #default="scope">
                  ¥{{ formatPrice((scope.row.price || 0) * (scope.row.num || 0)) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button
                      type="text"
                      color="#ff4d4f"
                      @click="removeSelectedGoods(scope.index)"
                      icon="Delete"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 已选商品总价 -->
            <div class="selected-total-price" v-if="selectedGoodsList.length > 0">
              <span>已选商品总价：</span>
              <span class="total-price">¥{{ formatPrice(totalPrice) }}</span>
            </div>
          </el-card>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleCancel" size="">取消</el-button>
          <el-button type="primary" @click="submitForm" size="" :loading="isLoading">
            <template #loading>提交中...</template>
            提交团购
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick} from 'vue';
import {ElMessage, ElDivider, ElIcon, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import server from "../utils/request.js";
import {ShoppingCart, Delete} from '@element-plus/icons-vue';
import {getUserIdFromToken} from "../utils/jwtUtil.js";

// 路由相关
const router = useRouter();

// 核心变量
const merchantId = getUserIdFromToken(); // 从JWT获取商户ID
const isLoading = ref(false); // 加载状态
const groupBuyForm = ref(null); // 表单实例

// 表单数据
const formData = ref({
  merchantId: merchantId || '', // 商户ID（自动填充）
  name: '', // 团购名称
  description: '', // 团购描述
  price: 0, // 团购原价
  discount: 0, // 团购折扣价
  personNum: 1, // 每单限制人数
});

// 商品相关变量
const merchantGoodsList = ref([]); // 商户商品库列表（无分页，加载所有）
const selectedGoodsList = ref([]); // 已选商品列表
const totalPrice = ref(0); // 已选商品总价

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入团购活动名称', trigger: 'blur'},
    {min: 2, max: 50, message: '名称长度在 2-50 个字符之间', trigger: 'blur'}
  ],
  description: [
    {max: 500, message: '描述不能超过 500 个字符', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入团购原价', trigger: 'blur'},
    {type: 'number', min: 0.01, message: '原价必须大于 0', trigger: 'blur'}
  ],
  discount: [
    {required: true, message: '请输入团购折扣价', trigger: 'blur'},
    {type: 'number', min: 0.01, message: '折扣价必须大于 0', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value >= formData.value.price) {
          callback(new Error('折扣价必须小于原价'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  personNum: [
    {required: true, message: '请输入每单限制人数', trigger: 'blur'},
    {type: 'number', min: 1, message: '限制人数至少为 1', trigger: 'blur'}
  ]
});

// 页面挂载逻辑
onMounted(() => {
  // 校验商户ID（必须存在）
  if (!merchantId) {
    ElMessageBox.alert('未获取到商户信息，请重新登录', '登录失效', {
      type: 'error',
      confirmButtonText: '去登录',
      callback: () => {
        router.push('/login');
      }
    });
    return;
  }

  // 查询商户商品库（加载所有商品，无分页）
  fetchMerchantGoods();
});

// 格式化价格（保留两位小数）
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
};

// 查询商户商品库（无分页）
const fetchMerchantGoods = async () => {
  isLoading.value = true;
  try {
    // 调用后端接口：根据merchantId查询所有商品（无需分页参数）
    const {data} = await server.get(`/goods/merchant/${merchantId}`);
    if (data.code === 200) {
      merchantGoodsList.value = data.data || []; // 直接接收所有商品列表
    } else {
      ElMessage.error('查询商品库失败：' + (data.msg || '未知错误'));
    }
  } catch (error) {
    console.error('查询商品库异常：', error);
    ElMessage.error('网络错误，加载商品失败');
  } finally {
    isLoading.value = false;
  }
};

// 处理商品勾选（添加到已选列表）
const handleGoodsSelection = (selectedRows) => {
  // 去重：避免重复勾选同一商品
  const newSelectedGoods = selectedRows.map(goods => ({
    id: goods.id,
    name: goods.name,
    price: goods.price,
    stock: goods.stock,
    num: 1 // 默认选择数量1
  }));

  // 合并已选商品（去重）
  const goodsMap = new Map();
  // 保留已选商品的数量（避免勾选后覆盖数量）
  selectedGoodsList.value.forEach(item => {
    goodsMap.set(item.id, item);
  });
  // 添加新勾选的商品
  newSelectedGoods.forEach(item => {
    if (!goodsMap.has(item.id)) {
      goodsMap.set(item.id, item);
    }
  });
  // 更新已选列表
  selectedGoodsList.value = Array.from(goodsMap.values());

  // 计算总价
  calculateTotalPrice();
};

// 计算已选商品总价
const calculateTotalPrice = () => {
  totalPrice.value = selectedGoodsList.value.reduce((total, item) => {
    const itemPrice = Number(item.price) || 0;
    const itemNum = Number(item.num) || 0;
    return total + itemPrice * itemNum;
  }, 0);
};

// 移除已选商品
const removeSelectedGoods = (index) => {
  selectedGoodsList.value.splice(index, 1);
  calculateTotalPrice();
  // 重置商品库中该商品的勾选状态（关键：避免勾选状态残留）
  nextTick(() => {
    const removedGoods = selectedGoodsList.value[index];
    if (removedGoods) {
      const targetRow = merchantGoodsList.value.find(item => item.id === removedGoods.id);
      if (targetRow) {
        // 获取表格实例，取消勾选
        const table = document.querySelector('.el-table__header-wrapper').parentNode.__vue__;
        table.toggleRowSelection(targetRow, false);
      }
    }
  });
};

// 提交表单
const submitForm = async () => {
  try {
    // 1. 表单验证
    await groupBuyForm.value.validate();

    // 2. 校验已选商品
    if (selectedGoodsList.value.length === 0) {
      ElMessage.error('请至少选择1件商品');
      return;
    }

    // 3. 校验商品数量
    const invalidGoods = selectedGoodsList.value.find(item =>
        !item.num || item.num < 1 || item.num > item.stock
    );
    if (invalidGoods) {
      ElMessage.error(`商品「${invalidGoods.name}」的数量无效（需1-${invalidGoods.stock}之间）`);
      return;
    }

    // 4. 构造提交数据
    const submitData = {
      ...formData.value,
      // 已选商品：仅携带id和数量（后端关联商品信息）
      goodsList: selectedGoodsList.value.map(item => ({
        id: item.id,
        num: item.num,
        merchantId: merchantId
      }))
    };

    // 5. 提交请求
    isLoading.value = true;
    const {data} = await server.post('/groupBuy', submitData);
    if (data.code === 200) {
      ElMessage.success('团购新增成功！');
      router.push('/merchantGroupBuyList'); // 跳转到团购列表页
    } else {
      ElMessage.error(`新增失败：${data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('表单提交失败：', error);
    ElMessage.error('表单验证失败，请检查填写内容');
  } finally {
    isLoading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm(
      '当前填写内容尚未保存，是否放弃并返回？',
      '放弃新增',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(() => {
    router.push('/merchantGroupBuyList');
  }).catch(() => {
  });
};
</script>

<style scoped>
/* 基础样式 */
.group-buy-add-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.group-buy-form {
  padding: 20px 0;
}

/* 分割线样式 */
.el-divider--content-center .el-divider__text {
  font-size: 16px;
  font-weight: 500;
  color: #1f2329;
  margin: 16px 0;
}

/* 商品选择区域 */
.goods-select-section {
  margin: 20px 0 30px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

/* 无商户商品提示 */
.no-merchant-goods {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

/* 无已选商品提示 */
.no-selected-goods {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

/* 图标样式 */
.icon {
  font-size: 32px;
  color: #c0c4cc;
  margin-bottom: 12px;
  display: inline-block;
}

/* 已选商品总价 */
.selected-total-price {
  text-align: right;
  margin-top: 16px;
  font-size: 15px;
  color: #1f2329;
  font-weight: 500;
}

.total-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 16px;
  margin-left: 8px;
}

/* 表单提示 */
.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
}

/* 操作按钮区域 */
.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 删除按钮样式 */
::v-deep .el-button--text {
  opacity: 1 !important;
  pointer-events: auto !important;
  color: #ff4d4f !important;
  cursor: pointer !important;
}

::v-deep .el-button--text:hover {
  color: #ff7875 !important;
  background-color: rgba(255, 77, 79, 0.05) !important;
}

/* 输入框优化 */
.el-input {
  width: 100%;
}

.el-input:focus-within .el-input__wrapper {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  border-color: #409eff;
}

/* 表格单元格内边距优化 */
::v-deep .el-table__cell {
  padding: 10px 0;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .group-buy-add-container {
    padding: 16px;
  }

  .el-table-column {
    width: auto !important;
    min-width: 80px;
  }
}
</style>